Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Monotonic Array

Problem Statement

Given an array nums containing integers, return true if the given array is monotonic. Otherwise, return false.

An array is monotonic if it follows below conditions.

  • An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
  • An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].

Examples

  • Example 1:

    • Input: nums = [1, 5, 10, 10, 15, 16, 90]
    • Expected Output: true
    • Justification: The array consistently ascends or remains equal, thus it is monotone increasing.
  • Example 2:

    • Input: nums = [9, 4, 2, 2, 0]
    • Expected Output: true
    • Justification: The array values either decrease or stay the same throughout, making it monotone decreasing.
  • Example 3:

    • Input: nums = [7, 8, 7, 7]
    • Expected Output: false
    • Justification: Array is not monotonic as 8 is in between two 7.

Solution

To solve this problem, we start by recognizing that a monotonic array has one of two characteristics: it's either entirely non-decreasing or entirely non-increasing. This observation is crucial because it allows us to simplify our checks to just two conditions across the array's entirety. We believe this approach is effective because it directly leverages the definition of monotonic arrays, enabling us to verify the condition with a single pass through the array. By evaluating adjacent elements from start to finish, we can determine if the array deviates from either monotonic condition. This method is efficient and straightforward, making it an ideal solution.

In the first step, we'll assess if the array is non-decreasing by comparing each element to its successor. Similarly, we'll check if it's non-increasing. If either condition holds for the entire array, our function will return true; otherwise, false. This dual-path check ensures we correctly handle arrays that are constant or have equal elements throughout, aligning with our monotonic criteria.

Step-by-Step Algorithm

  1. Initialize Two Flags: Start by declaring two boolean variables, isNonDecreasing and isNonIncreasing, and set them both to true. These flags will help us track whether the array is non-decreasing or non-increasing, respectively.

  2. Iterate Through the Array: Loop through the array from the first element to the second-last element. We compare each element with its next element to determine the array's trend. This is because we need at least two elements to compare and determine a trend.

  3. Check Non-Decreasing Trend: During each iteration, compare the current element with the next element. If the current element is greater than the next element, set isNonDecreasing to false. This indicates that the array cannot be non-decreasing because we found at least one instance where a later element is smaller than its predecessor.

  4. Check Non-Increasing Trend: Similarly, if the current element is less than the next element, set isNonIncreasing to false. This step checks for a non-increasing trend. Finding a later element larger than its predecessor means the array cannot be non-increasing.

  5. Determine Monotonicity: After completing the loop, check the flags. If either isNonDecreasing or isNonIncreasing is still true, the array is monotonic. Return true in this case. If both flags are false, the array is not monotonic, so return false.

Algorithm Walkthrough

Let's consider the input: nums = [1, 5, 10, 10, 15, 16, 90]

  1. Initialize Flags:

    • isNonDecreasing = true
    • isNonIncreasing = true
  2. First Iteration (1 -> 5):

    • Compare 1 and 5: Since 1 < 5, the array might be non-decreasing. Change isNonIncreasing to false.
  3. Second Iteration (5 -> 10):

    • Compare 5 and 10: Since 5 < 10, still possibly non-decreasing. No change to flags.
  4. Third Iteration (10 -> 10):

    • Compare 10 and 10: Equal elements do not affect monotonicity. No change to flags.
  5. Fourth Iteration (10 -> 15):

    • Compare 10 and 15: Since 10 < 15, the array continues to potentially be non-decreasing. No change to flags.
  6. Fifth Iteration (15 -> 16):

    • Compare 15 and 16: 15 < 16 supports non-decreasing trend. No change to flags.
  7. Sixth Iteration (16 -> 90):

    • Compare 16 and 90: 16 < 90 continues to support a non-decreasing trend. No change to flags.
  8. Determine Monotonicity:

    • After the final iteration, isNonDecreasing is false, and isNonIncreasing remains true.
    • Since isNonIncreasing is true, the array [1, 5, 10, 10, 15, 16, 90] is determined to be monotonic.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the length of the input array. This is because the algorithm iterates through the array exactly once to check if it is either non-decreasing or non-increasing.

Space Complexity

The space complexity complexity of the algorithm is . The algorithm uses a fixed amount of space (a couple of boolean variables) regardless of the input array size, indicating constant space complexity.

Monotonic Array (easy)
Count Nodes Equal to Average of Subtree (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity